"use strict";

QuickPasswordsMobile.Util = {
	logTime: function() {
		let timePassed = '';
		let end, endTime, elapsed;
		try {
			end = new Date();
			endTime = end.getTime();
			elapsed = new String(endTime  - this.lastTime); // time in milliseconds
			timePassed = '[' + elapsed + ' ms]   ';
			this.lastTime = endTime; // remember last time
		}
		catch(e) {;}
		return end.getHours() + ':' + end.getMinutes() + ':' + end.getSeconds() + '.' + end.getMilliseconds() + '  ' + timePassed;
	},

	logToConsole: function (msg, optionTitle) {
		if (this.ConsoleService == null)
		  this.ConsoleService = Components.classes["@mozilla.org/consoleservice;1"]
		                             .getService(Components.interfaces.nsIConsoleService);

		let title = "QuickPasswordsMobile ";
		title += (typeof optionTitle != 'undefined') ? '{' + optionTitle.toUpperCase() + '}' : '';
		this.ConsoleService.logStringMessage(title + " " + this.logTime() + "\n"+ msg);
	},

	logDebug: function (msg) {
	  if (QuickPasswordsMobile.Preferences.isDebug)
	    this.logToConsole(msg);
	},

	logDebugOptional: function (option, msg) {
	  if (QuickPasswordsMobile.Preferences.isDebugOption(option))
	    this.logToConsole(msg, option);
	},

	logError: function (aMessage, aSourceName, aSourceLine, aLineNumber, aColumnNumber, aFlags)
	{
	  // definition of flags, see flag constants:
		// const unsigned long errorFlag = 0x0; /** message is warning */ 
		// const unsigned long warningFlag = 0x1;  /** exception was thrown for this case - exception-aware hosts can ignore */ 
		// const unsigned long exceptionFlag = 0x2;
	  let consoleService = Components.classes["@mozilla.org/consoleservice;1"]
	                                 .getService(Components.interfaces.nsIConsoleService);
	  let aCategory = '';

	  let scriptError = Components.classes["@mozilla.org/scripterror;1"].createInstance(Components.interfaces.nsIScriptError);
	  scriptError.init(aMessage, aSourceName, aSourceLine, aLineNumber, aColumnNumber, aFlags, aCategory);
	  consoleService.logMessage(scriptError);
	} ,

	logException: function (aMessage, ex) {
		let stack = ''
		if (typeof ex.stack!='undefined')
			stack= ex.stack.replace("@","\n  ");
		// let's display a caught exception as a warning.
		let fn = ex.fileName ? ex.fileName : "?";
		this.logError(aMessage + "\n" + ex.message, fn, stack, ex.lineNumber, 0, 0x1);
	},
	
	logWarning: function (aMessage, fn) {
	  this.logError(aMessage, fn, null, 0, 0, 0x1);
	} 
}
